#!/usr/bin/env ruby
# -*- coding: utf-8 -*-

# -------------------------------------------------------------------------- #
# Copyright 2002-2011, OpenNebula Project Leads (OpenNebula.org)             #
#                                                                            #
# Licensed under the Apache License, Version 2.0 (the "License"); you may    #
# not use this file except in compliance with the License. You may obtain    #
# a copy of the License at                                                   #
#                                                                            #
# http://www.apache.org/licenses/LICENSE-2.0                                 #
#                                                                            #
# Unless required by applicable law or agreed to in writing, software        #
# distributed under the License is distributed on an "AS IS" BASIS,          #
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   #
# See the License for the specific language governing permissions and        #
# limitations under the License.                                             #
#--------------------------------------------------------------------------- #
$: << File.dirname(__FILE__)

require 'xml-parser.rb'
require 'vboxrc.rb'
require 'actions.rb'


# steps
# 2- take snapshot (with pause)
# 3- save snapshot
# 4- tar domain+snapshot into $2
# 5- cancel machine

vmid = ARGV[0]
init nil,vmid
uuid = get_uuid
checkpoint = ARGV[1]
domain = domain_filename @vmname

rc = save_state

#if save_state fails (i.e. VM not running), the VM will not be cancelled.
`#{File.dirname(__FILE__)}/packState.sh #{domain} #{@vmname} #{uuid} #{checkpoint}` if rc==0
rc = $?.exitstatus
rc = power_off if rc == 0
until powered_off? do sleep 1 end if rc == 0
rc = storage_dettach if rc == 0
rc = close_mediums if rc == 0
rc = unregister if rc == 0
remove_domain @vm_name if rc == 0

exit rc


#TODO deal with snapshot (in bash)?
#1 - find snapshot uuid
#2 - copy snapshot uuid to domain
#3 - tar domain+snapshot files with domain
#4 - delete snapshot files
#`cancel` #TODO find nicer way to cancel
